﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.IdentityModel.Tokens;
using SQLiteCoreDB.Common;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using WebFile.Models;

namespace WebFile.Filter
{
    /// <summary>
    /// 登录过滤器
    /// </summary>
    public class LoginFilter : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext context)
        {

            var token = context.HttpContext.Request.Cookies[KeyValueConfig.Cookie_Token];
            // 获取当前请求的控制器和操作方法
            var controller = context.RouteData.Values["controller"]?.ToString();
            //Console.WriteLine(token);
            if (token == null && !IsValidToken(token))
            {

                // 判断是否是登录页的控制器和操作方法
                if (controller == "LoginHandle") return;
                
                //context.Result = new RedirectToActionResult("LoginHandle", "LoginView", null);
                context.Result = new RedirectResult("/LoginHandle/LoginView"); return;
            }

            //if (!LoginMode.admin)
            //{
            //    context.HttpContext.Response.StatusCode = 403;
          

            //    // 判断是否是登录页的控制器和操作方法
            //    if (controller == "LoginHandle") return;

            //    context.Result = new RedirectResult("/LoginHandle/P403");  return;
            //}
            base.OnActionExecuting(context);
        }

        private bool IsValidToken(string token)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var validationParameters = GetValidationParameters();

            SecurityToken validatedToken;
            try
            {
                // 验证JWT的有效性
                tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
            }
            catch (Exception)
            {
                return false;
            }

            var jwt = tokenHandler.ReadJwtToken(token);
            var tokenName = jwt.Claims.FirstOrDefault(claim => claim.Type == ClaimTypes.Name && claim.Value.Equals(LoginMode.username));
            if (tokenName != null && validatedToken.ValidTo >= DateTime.UtcNow)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private TokenValidationParameters GetValidationParameters()
        {
            return new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,

                ValidIssuer = KeyValueConfig.issuer,
                ValidAudience = KeyValueConfig.audience,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(KeyValueConfig.TokeKey))
            };
        }
    }
}